//创建相册
async function createAlbum(){                        //防止相册重名
  let albumName=prompt("请输入相册名称","abc");
  $(".list-group-item").each(function(){
    if (this.id === ("album-"+albumName)){
      alert("相册名称重复，请重新输入。");
      albumName = "";
    }
  });
  if (albumName != null && albumName != ""){              //相册名不能为空值
    await fetch("/creatAlbum",{
      method:"POST",
      body: JSON.stringify({albumName}),
      credentials:"include",
      headers:{
        "Content-Type":"application/json"
      }
    }).catch(e => console.log("error", e));
    location.href="/";
  }
}
//
//删除相册
async function deleteAlbum(event){
  var ans = confirm("确定删除该相册吗？");
  if (ans){
    const albumName = $(event).prev().text();
    if(albumName === "default"){
      alert("default相册不可以被删除。");
    }
    await fetch("/deleteAlbum",{
      method:"POST",
      body: JSON.stringify({albumName}),
      credentials:"include",
      headers:{
        "Content-Type":"application/json"
      }
    }).catch(e => console.log("error", e));
    location.href="/";
  }
}
//
//选择相册
async function changeAlbum(event){
  const albumName = event.target.innerText.slice(0,-2);
  console.log("被选相册为", albumName);
  await fetch("/changeAlbum",{
    method:"POST",
    body: JSON.stringify({albumName}),
    credentials:"include",
    headers:{
      "Content-Type":"application/json"
    }
  }).catch(e => console.log("error", e));
  location.href="/";
}
//
//添加图片
function createReader(cb) {
  return function(event) {
    const file = event.target.files[0];
    const fr = new FileReader();
    fr.onload = function() {
      imgSrc = fr.result;
      cb(imgSrc);
    }
    fr.readAsDataURL(file);
  }
}
async function readImage(imgSrc){
  await fetch("/readImage",{
    method:"POST",
    body: JSON.stringify({imgSrc}),
    credentials:"include",
    headers:{
      "Content-Type":"application/json"
    }
  }).catch(e => console.log("error", e));
  location.href="/";
}
//
//删除图片及图片框
async function deleteImage(event){
  var ans = confirm("确定删除该图片吗？");
  if (ans) {
    const photoId = $(event).prev().attr("id");
    console.log("photoId=",photoId)
    await fetch("/deleteImage",{
        method:"POST",
        body: JSON.stringify({photoId}),
        credentials:"include",
        headers:{
          "Content-Type":"application/json"
        }
    }).catch(e => console.log("error", e));
    location.href="/";
  }
}
//
// 轮播
$(".img-thumbnail").click(function(){
  const photoId = event.target.id;
  $("#myModal").modal('toggle');
  $(".carousel-item[name="+photoId+"]").addClass("active");
  $(".carousel-control-prev").click(function(){
    $("#carousel").carousel('prev');
  });
  $(".carousel-control-next").click(function(){
    $("#carousel").carousel('next');
  });
});
